<?php
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\AdminUser as User;
use App\Models\SmsTemplate;
class SmsTemplateController extends Controller
{
    protected $fields = [
		'title' => '',
        'content' => '',
        'aid' => 0,
		'status' => 1,
		'is_query' => 0,
		'terrace'=>'阿里大鱼'
    ];

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data 			= array();
            $data['draw'] 	= $request->get('draw');
            $start 			= $request->get('start');
            $length 		= $request->get('length');
            $order 			= $request->get('order');
            $columns 		= $request->get('columns');
            $search 		= $request->get('search');
			$uid 			= auth()->user()->id;
			$count 			= SmsTemplate::where(function ($query) use ($uid){
									if($uid!=1){
										$query->where('uid','=',$uid);
									}
								})->count();
            $data['recordsTotal'] = $count;
            if (strlen($search['value']) > 0) {
                $data['recordsFiltered'] 	= SmsTemplate::where(function ($query) use ($search) {
												$query->where('name', 'LIKE', '%' . $search['value'] . '%');
											})->where(function ($query) use ($uid){
												if($uid!=1){
													$query->where('uid','=',$uid);
												}
											})->count();
				
                $data['data'] 				= SmsTemplate::where(function ($query) use ($search) {
													$query->where('wechat_values.name', 'LIKE', '%' . $search['value'] . '%');
												})
												->where(function ($query) use ($uid){
													if($uid!=1){
														$query->where('uid','=',$uid);
													}
												})
												->skip($start)->take($length)
												->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
												->get();
            } else {
				$data['recordsFiltered'] 	= $count;						
                $data['data'] 				= SmsTemplate::where(function ($query) use ($uid){
													if($uid!=1){
														$query->where('wechat_values.uid','=',$uid);
													}
												})
												->skip($start)->take($length)
												->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
												->get();
            }
            return response()->json($data);
        }
        return view('admin.smstemplate.index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $data = [];
        foreach ($this->fields as $field => $default) {
            $data[$field] = old($field, $default);
        }
        return view('admin.smstemplate.create', $data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $tag = new SmsTemplate();
        foreach (array_keys($this->fields) as $field) {
			if($field=='aid'){
				$tag->$field = auth()->user()->id;
				continue;
			}
			if($field=='status'){
				$tag->$field = $request->get($field)==null?0:$request->get($field);
				continue;
			}
			$tag->$field = $request->get($field)==null?$this->fields[$field]:$request->get($field);
        }
		$tag->save();
		if($request->get('is_query')==1){
			SmsTemplate::where('aid',auth()->user()->id)->where('id','<>',$tag->id)->where('is_query',1)->update(['is_query'=>0]);
		}
		event(new \App\Events\userActionEvent('\App\Models\SmsTemplate',$tag->id, 1, '新增了短信模板['.$tag->title.']' ));
        return redirect('/admin/smstemplate')->withSuccess('添加成功！');
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
       $tag 				= SmsTemplate::find((int)$id);
       if (!$tag) return redirect()->back()->withErrors("找不到该调用值!");
       foreach (array_keys($this->fields) as $field) {
           $data[$field] 	= old($field, $tag->$field);
       }
	   $data['id']			= $id;
       return view('admin.smstemplate.edit', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
		//if($this->validateValue($request->wechat_id,$request->key)>0&&$this->validateValue($request->wechat_id,$request->key)!=$id){ return redirect()->back()->withErrors('key重复！');}
		
        $tag = SmsTemplate::find((int)$id);
        foreach (array_keys($this->fields) as $field) {
			if($field=='aid'){
				continue;
			}
            $tag->$field = $request->get($field);
        }
        $tag->save();
		if($request->get('is_query')==1){
			SmsTemplate::where('aid',auth()->user()->id)->where('id','<>',$tag->id)->update(['is_query'=>0]);
		}
		event(new \App\Events\userActionEvent('\App\Models\SmsTemplate',$id, 3, '更新短信模板['.$tag->title.']'));
        return redirect('/admin/smstemplate/')->withSuccess('更新成功！');
    }
    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id or string ids=>1,2,3,4,5,6
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if(is_numeric($id)){
            $tag = SmsTemplate::find((int)$id);
            if ($tag) {
				$key = $tag->title;
                $tag->delete();
				event(new \App\Events\userActionEvent('\App\Models\SmsTemplate',$id, 2, '删除了调用值['.$key.']'));
            } else {
                return redirect()->back()
                    ->withErrors("删除失败");
            }
        }else{
            $idArr = explode(',',$id);
			$wvs =  SmsTemplate::select('title')->whereIn('id',$idArr)->get();
			$wx = "[";
			foreach($wvs as $wv){ $wx.=$wv->title."、";}
			$wx .="]";
            $recordRow =SmsTemplate::whereIn('id',$idArr)->delete();
			event(new \App\Events\userActionEvent('\App\Models\SmsTemplate',$id, 2, '批量短信模板'.$wx));
            if(!$recordRow){
                return redirect()->back()
                    ->withErrors("删除失败");
            }
        }
        return redirect()->back()
            ->withSuccess("删除成功");
    }
	function validateValue($id,$key){
		$tag = SmsTemplate::where('id',$id)->where('title',$key)->first();
		if(!$tag){
			return 0;
		}else{
			return $tag->id;
		}
	}
	
}